cc.Class({
    extends: cc.Component,

    properties: {
        initIndex: 0, // 负值不初始化状态
        buttonArray: [cc.Button],

        _currentIndex: -1,
    },
    editor: {
        menu: 'ExtendUI/RadioButton'
    },

    // use this for initialization
    onLoad: function () {
        this.buttonArray.forEach((button) => {
            button.node.on('click', this.onClick, this);
        });
    },

    start: function() {
        this.setState(this.initIndex);
    },

    pushNode: function(buttonNode) {
        this.buttonArray.push(buttonNode.getComponent(cc.Button));
        buttonNode.on('click', this.onClick, this);
    },

    setState: function(index) {
        if (index >= 0 && index < this.buttonArray.length) {
            this._currentIndex = index;
            this.buttonArray[index].node.emit('touchstart');
            this.buttonArray[index].node.emit('touchend');
        }
        else if (this._currentIndex >= 0 && this._currentIndex < this.buttonArray.length) {
            var button = this.buttonArray[this._currentIndex];
            button.interactable = true;
            button.node.emit('click_cancel');
        }
    },
    
    onClick: function(event) {
        var targetButton = event.target.getComponent(cc.Button);
        this.buttonArray.forEach((button) => {
            if (button === targetButton) {
                button.interactable = false;
            }
            else {
                button.interactable = true;
                button.node.emit('click_cancel');
            }
        });
    }
});